/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "i2c.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "mpu6050.h"
#include "key.h"
#include "string.h"
#include "stdio.h"
#include "NanoEdgeAI.h"
#include "knowledge.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
KEY_State_t tttt;
uint8_t similarity = 0 ;

#define WORK_MODE 1
#if WORK_MODE==0
#define GET_DATA_MODE 0
#else
#define PREDICT_DATA_MODE 1
#endif

typedef struct
{
	float data[AXIS_NUMBER*DATA_INPUT_USER];
	uint16_t cnt;
	uint16_t front;
	uint16_t rear;
}Queue_Data_t;
float input_buffer[AXIS_NUMBER*DATA_INPUT_USER];


/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
uint8_t insert_queue(Queue_Data_t* queue, MPU6050_Data_t* new_data) {
    if (queue == NULL || new_data == NULL) {
        return 1;
    }
		
		uint16_t insert_idx = queue->rear * AXIS_NUMBER;
		queue->data[insert_idx + 0] = new_data->Accel_X;
		queue->data[insert_idx + 1] = new_data->Accel_Y;
		queue->data[insert_idx + 2] = new_data->Accel_Z;

    queue->rear = (queue->rear + 1) % DATA_INPUT_USER;

    if (queue->cnt < DATA_INPUT_USER) {
        queue->cnt++;
    }
	else {
        queue->front = (queue->front + 1) % DATA_INPUT_USER;
    }

    return 0;
}

uint16_t get_queue(Queue_Data_t* queue, float* output_buffer)
{
		if (queue == NULL || output_buffer == NULL) {
        return 0;
    }
		
	int total_floats = 0;
    int current_group = queue->front;

    for (int i = 0; i < queue->cnt; i++) {
        int src_idx = current_group * AXIS_NUMBER;
        int dst_idx = total_floats;

        for (int j = 0; j < AXIS_NUMBER; j++) {
            output_buffer[dst_idx + j] = queue->data[src_idx + j];
        }

        total_floats += AXIS_NUMBER;
        current_group = (current_group + 1) % DATA_INPUT_USER;
    }

    return total_floats;
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_I2C1_Init();
  MX_USART1_UART_Init();
  MX_TIM2_Init();
  MX_TIM1_Init();
  /* USER CODE BEGIN 2 */
	MPU6050_Init(Sensor_I2C2_Serch());
	HAL_TIM_Base_Start_IT(&htim2);
	HAL_TIM_Base_Start_IT(&htim1);
	
    HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_1);
	 __HAL_TIM_SetCompare(&htim1, TIM_CHANNEL_1, 2000);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  char str[32];
	#if WORK_MODE==GET_DATA_MODE
	volatile uint16_t send_cnt = 0;
	while(1)
	{
		if((tttt = key_getVal()) == press){
			HAL_Delay(3000);
			break;
		}
	}
	#elif WORK_MODE==PREDICT_DATA_MODE
	if(neai_anomalydetection_init()!=NEAI_OK)
	{
		Error_Handler();
	}
	volatile uint8_t data_cnt=0;
	volatile uint8_t learn_cnt=0;
	uint8_t similarity = 0 ;
	Queue_Data_t mpu6050_queue; 
	#endif
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		HAL_Delay(2);
		MPU6050_Read_Accel();
		
		#if WORK_MODE==GET_DATA_MODE
		if((tttt=key_getVal())==press){
			send_cnt+=16;
		}
		if(send_cnt)
		{
			send_cnt -=1;
			if(send_cnt %16==0)
				sprintf(str, "%f,%f,%f\r\n",Mpu6050_Data.Accel_X,Mpu6050_Data.Accel_Y,Mpu6050_Data.Accel_Z);
			else
				sprintf(str, "%f,%f,%f,",Mpu6050_Data.Accel_X,Mpu6050_Data.Accel_Y,Mpu6050_Data.Accel_Z);
			HAL_UART_Transmit_DMA(&huart1, (const uint8_t*)str, strlen(str));
		}
		#elif WORK_MODE==PREDICT_DATA_MODE
		insert_queue(&mpu6050_queue, &Mpu6050_Data);
		data_cnt += 1;
		if(mpu6050_queue.cnt<DATA_INPUT_USER)continue;
		if(data_cnt%(DATA_INPUT_USER/2)==0)
		{
			data_cnt = 0;
			get_queue(&mpu6050_queue, input_buffer);
			if(learn_cnt++<MINIMUM_ITERATION_CALLS_FOR_EFFICIENT_LEARNING){
			    neai_anomalydetection_learn(input_buffer);
				HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,1);
			}
			else{
			    neai_anomalydetection_detect(input_buffer,&similarity);
				sprintf(str,"similarity:%d\r\n",similarity);
				HAL_UART_Transmit_DMA(&huart1, (const uint8_t*)str, strlen(str));
				if(similarity<=99){
				   HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,GPIO_PIN_RESET);
					HAL_Delay(2);
					HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,GPIO_PIN_SET);
				}
			}
		}
		#endif
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if(htim->Instance == TIM2)
	{
		key_scan();
	}
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
